package com.css.zfzx.fwsjcj.modules.structure.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.components.attach.repository.entity.SysAttachmentEntity;
import com.css.bpm.platform.components.attach.service.SysAttachment;
import com.css.bpm.platform.org.division.repository.entity.DivisionEntity;
import com.css.bpm.platform.org.user.repository.entity.UserEntity;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.bpm.platform.utils.UUIDGenerator;
import com.css.zfzx.fwsjcj.cache.DivisionCache;
import com.css.zfzx.fwsjcj.commen.util.Constant;
import com.css.zfzx.fwsjcj.commen.util.EasyPoiExcelUtil;
import com.css.zfzx.fwsjcj.modules.analysis.vo.AnalysisQueryVo;
import com.css.zfzx.fwsjcj.modules.structure.entity.*;
import com.css.zfzx.fwsjcj.modules.structure.repository.FwStructureFormRepository;
import com.css.zfzx.fwsjcj.modules.structure.repository.FwWoodStructureRepository;
import com.css.zfzx.fwsjcj.modules.structure.service.FwStructureFormService;
import com.css.zfzx.fwsjcj.modules.structure.service.FwWoodStructureService;
import com.css.zfzx.fwsjcj.modules.structure.verify.BrickStructureCheck;
import com.css.zfzx.fwsjcj.modules.structure.verify.WoodStructureCheck;
import com.css.zfzx.fwsjcj.modules.structure.vo.FwWoodStructureVo;
import com.css.zfzx.fwsjcj.modules.structure.vo.StructureQueryVo;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author leon
 * @Title: FwWoodStructureServiceImpl
 * @Description: 木结构
 * @date 2020/6/4 15:23
 */
@Slf4j
@Service
public class FwWoodStructureServiceImpl implements FwWoodStructureService {
    @Autowired
    private FwWoodStructureRepository woodStructureRepository;
    @Autowired
    private JPAQueryFactory jpaQueryFactory;
    @Autowired
    private FwStructureFormService structureFormService;

    @Autowired
    private FwStructureFormRepository fwStructureFormRepository;

    private volatile static HashMap<String, List> divisionMap;
    @Resource
    private SysAttachment sysAttachment;

    @Override
    public void save(FwWoodStructureEntity fwWoodStructureEntity) {
        String userId = PlatformSessionUtils.getUserId();
        UserEntity user = PlatformAPI.getOrgAPI().getUserAPI().getUser(userId);
        /**
         * 砖石结构子表设置默认值（子表保存）
         */
        fwWoodStructureEntity.setId(UUIDGenerator.getUUID());
        // 数据收集人名称
        fwWoodStructureEntity.setCollectUser(user.getUserName());
        // 存数据收集人ID
        fwWoodStructureEntity.setCreateUser(userId);
        fwWoodStructureEntity.setCreateTime(new Date());
        fwWoodStructureEntity.setDelFlag(Constant.DEL_NO);
        woodStructureRepository.save(fwWoodStructureEntity);

        /**
         * 主表保存
         */
        FwStructureFormEntity structureFormEntity = new FwStructureFormEntity();
        // 保存子表ID
        structureFormEntity.setStructureId(fwWoodStructureEntity.getId());
        // 保存子表类型
        structureFormEntity.setStructureType(Constant.WOOD_STRUCTURE);
        // 保存子表省、市、区县
        structureFormEntity.setBelongtoProvince(fwWoodStructureEntity.getBelongtoProvince());
        structureFormEntity.setBelongtoCity(fwWoodStructureEntity.getBelongtoCity());
        structureFormEntity.setBelongtoArea(fwWoodStructureEntity.getBelongtoArea());
        // 保存子表建筑名称
        structureFormEntity.setBuildingName(fwWoodStructureEntity.getBuildingName());
        // 保存子表建筑类型
        structureFormEntity.setSiteType(fwWoodStructureEntity.getSiteType());
        // 保存建筑编号
        structureFormEntity.setStructureNum(fwWoodStructureEntity.getWoodStructureNum());
        // 保存任务id和名称
        structureFormEntity.setTaskId(fwWoodStructureEntity.getTaskId());
        structureFormEntity.setTaskName(fwWoodStructureEntity.getTaskName());
        structureFormEntity.setBuildingArea(fwWoodStructureEntity.getBuildingArea()==null?0.0:fwWoodStructureEntity.getBuildingArea());
        structureFormEntity.setStatus(fwWoodStructureEntity.getStatus());
        structureFormService.save(structureFormEntity);
    }

    @Override
    @Transactional
    public void update(FwWoodStructureEntity fwWoodStructureEntity) {
        if (StringUtils.isEmpty(fwWoodStructureEntity.getId())) {
            throw new RuntimeException("修改ID不能为空");
        }
        // 获取当前用户信息
        String userId = PlatformSessionUtils.getUserId();
        UserEntity user = PlatformAPI.getOrgAPI().getUserAPI().getUser(userId);
        /**
         * 设置默认值
         */
        fwWoodStructureEntity.setUpdateUser(user.getUserId());
        fwWoodStructureEntity.setUpdateTime(new Date());
        // 将不为空的数据拷贝到旧数据中
        //FwWoodStructureEntity oldTarge = this.findById(fwWoodStructureEntity.getId());
        //  若审核状态为审核未通过改为未提交
        if(Constant.SP_NOT.equals(fwWoodStructureEntity.getStatus())){
            fwWoodStructureEntity.setStatus(Constant.NO_SUB);
            fwWoodStructureEntity.setCheckOpinion("");
            fwWoodStructureEntity.setCheckUser("");
        }
        //SpringUtil.copyPropertiesIgnoreEmpty(fwWoodStructureEntity, oldTarge);
        // 实体中必须有ID
        woodStructureRepository.save(fwWoodStructureEntity);
        /**
         * 主表保存
         */
        FwStructureFormEntity sourceStructureFormEntity = structureFormService.findStructureForm(Constant.WOOD_STRUCTURE, fwWoodStructureEntity.getId());
        //FwStructureFormEntity targetStructureFormEntity = sourceStructureFormEntity;
        // 保存子表省
        sourceStructureFormEntity.setBelongtoProvince(fwWoodStructureEntity.getBelongtoProvince());
        // 保存子表市
        sourceStructureFormEntity.setBelongtoCity(fwWoodStructureEntity.getBelongtoCity());
        // 保存子表区县
        sourceStructureFormEntity.setBelongtoArea(fwWoodStructureEntity.getBelongtoArea());
        // 保存子表建筑名称
        sourceStructureFormEntity.setBuildingName(fwWoodStructureEntity.getBuildingName());
        // 保存子表建筑类型
        sourceStructureFormEntity.setSiteType(fwWoodStructureEntity.getSiteType());
        // 若审核状态为审核未通过改为未提交
        if (Constant.SP_NOT.equals(sourceStructureFormEntity.getStatus())){
            sourceStructureFormEntity.setStatus(Constant.NO_SUB);
            sourceStructureFormEntity.setCheckUser("");
            sourceStructureFormEntity.setCheckOpinion("");
        }
        sourceStructureFormEntity.setStatus(fwWoodStructureEntity.getStatus());
        sourceStructureFormEntity.setBuildingArea(fwWoodStructureEntity.getBuildingArea()==null?0.0:fwWoodStructureEntity.getBuildingArea());
        structureFormService.update(sourceStructureFormEntity);

    }

    @Override
    @Transactional
    public JSONObject getPage(StructureQueryVo structureQueryVo, int curPage, int pageSize) {
        QFwWoodStructureEntity q = QFwWoodStructureEntity.fwWoodStructureEntity;
        Predicate predicate = q.isNotNull().or(q.isNull());

        // 查询条件
        if (structureQueryVo != null) {
            String buildingName = structureQueryVo.getBuildingName();
            predicate = ("".equals(buildingName) || buildingName == null) ? predicate : ExpressionUtils.and(predicate, q.buildingName.like("%" + buildingName + "%"));

            String belongtoProvince = structureQueryVo.getBelongtoProvince();
            predicate = ("".equals(belongtoProvince) || belongtoProvince == null) ? predicate : ExpressionUtils.and(predicate, q.belongtoProvince.like("%" + belongtoProvince + "%"));

            String belongtoCity = structureQueryVo.getBelongtoCity();
            predicate = ("".equals(belongtoCity) || belongtoCity == null) ? predicate : ExpressionUtils.and(predicate, q.belongtoCity.like("%" + belongtoCity + "%"));

            String siteType = structureQueryVo.getSiteType();
            predicate = ("".equals(siteType) || siteType == null) ? predicate : ExpressionUtils.and(predicate, q.siteType.like("%" + siteType + "%"));

            String status = structureQueryVo.getStatus();
            predicate = ("".equals(status) || status == null) ? predicate : ExpressionUtils.and(predicate, q.status.eq(status));

        }
        // 删除标识
        predicate = ExpressionUtils.and(predicate, q.delFlag.eq(Constant.DEL_NO));

        QueryResults<FwWoodStructureEntity> page = jpaQueryFactory
                .selectFrom(q)
                .where(predicate)
                .orderBy(q.createTime.desc())
                .offset(curPage - 1)   //起始页
                .limit(pageSize)  //每页大小
                .fetchResults();
        /**
         * 适配base转为JSONObject类型
         */
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", page.getResults());
        jsonObject.put("total", page.getTotal());
        return jsonObject;
    }

    @Override
    public void delete(String id) {
        FwWoodStructureEntity woodStructureEntity = woodStructureRepository.findById(id).get();
        woodStructureEntity.setDelFlag(Constant.DEL_YES);
        update(woodStructureEntity);
    }

    @Override
    public FwWoodStructureEntity findById(String id) {
        return woodStructureRepository.findById(id).get();
    }

    @Override
    public List<FwWoodStructureEntity> findAll() {
        return woodStructureRepository.findAll();
    }

    @Override
    @Transactional
    public void submit(List<String> idList) {
        QFwWoodStructureEntity q = QFwWoodStructureEntity.fwWoodStructureEntity;
        jpaQueryFactory.update(q)
                .set(q.status, Constant.DAI_SP)
                .where(q.id.in(idList))
                .execute();
    }
    public HashMap<String, List> divisionMap() {
        HashMap<String, List> map = new HashMap<>();
        // 所有省
        List<DivisionEntity> provinceDivisions = PlatformAPI.getDivisionAPI().getSubDivisions("root");
        for (DivisionEntity province : provinceDivisions) {
            String provinceName = province.getDivisionName();
            // 市
            List<DivisionEntity> cities = PlatformAPI.getDivisionAPI().getSubDivisions(province.getDivisionId());
            ArrayList<String> cityNames = new ArrayList<>();
            for (DivisionEntity city : cities) {
                String cityName = city.getDivisionName();
                cityNames.add(cityName);
                // 不为直辖市
                if (!"北京市".equals(provinceName) && !"天津市".equals(provinceName) && !"上海市".equals(provinceName) && !"重庆市".equals(provinceName)) {
                    // 获取市下面的区县
                    List<DivisionEntity> areas = PlatformAPI.getDivisionAPI().getSubDivisions(city.getDivisionId());
                    ArrayList<String> areaNames = new ArrayList<>();
                    for (DivisionEntity area : areas) {
                        String areaName = area.getDivisionName();
                        areaNames.add(areaName);
                    }
                    map.put(cityName, areaNames);
                }
            }
            // 省对应下面的市(直辖市-对应的是区)
            map.put(provinceName, cityNames);
        }
        return map;
    }
    @Override
    public String exportExcel(String taskName, String taskId, MultipartFile file, HttpServletResponse response) {
        // 单例初始化省市区map
        if (divisionMap == null) {
            synchronized (this) {
                if (divisionMap == null) {
                    divisionMap = divisionMap();
                }
            }
        }
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            params.setVerifyHandler(new WoodStructureCheck(divisionMap));
            // 获取到Excel数据
            ExcelImportResult<FwWoodStructureVo> result = ExcelImportUtil.importExcelMore(file.getInputStream(), FwWoodStructureVo.class, params);
            List<FwWoodStructureVo> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            // 重复后失败条数
            int failCount = saveStructure(taskName, taskId, list, sb);
            if (failCount > 0) {
                // result.getFailList().size()为保存时出错的条数
                int failList = firstList + result.getFailList().size() - list.size();
                returnMsg.append("成功导入" + (result.getList().size() - failCount) + "条，失败" + (failList + failCount) + "条<br/>");
                returnMsg.append("样本编码" + failCount + "存在重复数据<br/>");
                returnMsg.append(sb);
            } else {
                returnMsg.append("成功导入" + (result.getList().size() - failCount) + "条，失败" + (result.getFailList().size() + failCount) + "条<br/>");
                returnMsg.append(sb);
            }
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<FwWoodStructureVo> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    FwWoodStructureVo woodStructureVo = iterator.next();
                    String error = "";
                    returnMsg.append("第" + woodStructureVo.getRowNum() + "行" + woodStructureVo.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "导入失败，请检查数据正确性";
        }
    }

    @Transactional
    @Override
    public void updateFileId(String formId, String fileId) {
        FwWoodStructureEntity fwWoodStructureEntity = findById(formId);

        if (!StringUtils.isEmpty(fwWoodStructureEntity)) {
            woodStructureRepository.updateFile(formId, fileId);
        }
    }

    @Override
    public long count(AnalysisQueryVo analysisQueryVo) {
        Specification<FwWoodStructureEntity> specification = new Specification<FwWoodStructureEntity>() {
            @Override
            public javax.persistence.criteria.Predicate toPredicate(Root<FwWoodStructureEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<javax.persistence.criteria.Predicate> predicates = new ArrayList<>();
                if (analysisQueryVo != null) {
                    // 省
                    String belongtoProvince = analysisQueryVo.getBelongtoProvince();
                    if (!StringUtils.isEmpty(belongtoProvince)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoProvince"), belongtoProvince));
                    }
                    // 市
                    String belongtoCity = analysisQueryVo.getBelongtoCity();
                    if (!StringUtils.isEmpty(belongtoCity)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoCity"), belongtoCity));
                    }
                    // 区
                    String belongtoArea = analysisQueryVo.getBelongtoArea();
                    if (!StringUtils.isEmpty(belongtoArea)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoArea"), belongtoArea));
                    }
                    //建筑年代
                    String buildingAge = analysisQueryVo.getBuildingAge();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(buildingAge)) {
                        predicates.add(criteriaBuilder.equal(root.get("buildingAge"), buildingAge));
                    }
                    //任务名称
                    String taskName = analysisQueryVo.getTaskName();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(taskName)) {
                        String[] strArray = taskName.split(",");
                        List<String> list = Arrays.asList(strArray);
                        if (list != null && list.size() > 0){
                            predicates.add(root.get("taskName").in(list));
                        }
                    }
                    /*//抗震设防烈度
                    String nowFortificationIntensity = analysisQueryVo.getNowFortificationIntensity();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(nowFortificationIntensity)) {
                        predicates.add(criteriaBuilder.equal(root.get("fortifyStandard"), nowFortificationIntensity));
                    }*/
                    // 穿斗方式(横向穿斗贯穿整榀构架,无穿斗)
                    String cdType = analysisQueryVo.getCdType();
                    if (!StringUtils.isEmpty(cdType)) {
                        predicates.add(criteriaBuilder.equal(root.get("cdType"), cdType));
                    }
                    // 木柱梢径(大于150mm,小于等于150mm)
                    String mzsj = analysisQueryVo.getMzsj();
                    if (!StringUtils.isEmpty(mzsj)) {
                        predicates.add(criteriaBuilder.equal(root.get("mzsj"), mzsj));
                    }
                    // 围护墙体类型（土墙,砖墙,木板墙）
                    String wallType = analysisQueryVo.getWallType();
                    if (!StringUtils.isEmpty(wallType)) {
                        predicates.add(criteriaBuilder.equal(root.get("wallType"), wallType));
                    }
                    // 山尖墙体类型(土墙,砖墙,木板墙)
                    String sjqtType = analysisQueryVo.getSjqtType();
                    if (!StringUtils.isEmpty(sjqtType)) {
                        predicates.add(criteriaBuilder.equal(root.get("sjqtType"), sjqtType));
                    }
                    // 墙体厚度（按照≤120mm，120-240mm，240-360mm，≥360mm统计占比）
                    String wallThick = analysisQueryVo.getWallThick();
                    if (!StringUtils.isEmpty(wallThick)) {
                        if (Constant.LESS_120.equals(wallThick)) {
                            predicates.add(criteriaBuilder.le(root.get("wallThick"), 120));
                        }
                        if (Constant.BETWEEN_120_240.equals(wallThick)) {
                            predicates.add(criteriaBuilder.between(root.get("wallThick"), 120, 240));
                        }
                        if (Constant.BETWEEN_240_360.equals(wallThick)) {
                            predicates.add(criteriaBuilder.between(root.get("wallThick"), 240, 360));
                        }
                        if (Constant.MORE_360.equals(wallThick)) {
                            predicates.add(criteriaBuilder.ge(root.get("wallThick"), 360));
                        }
                    }
                    // 墙体圈梁（有圈梁,无圈梁）
                    String wallRingBeam = analysisQueryVo.getWallRingBeam();
                    if (!StringUtils.isEmpty(wallRingBeam)) {
                        predicates.add(criteriaBuilder.equal(root.get("wallRingBeam"), wallRingBeam));
                    }
                }
                // 有效标识，即为有效的
                predicates.add(criteriaBuilder.equal(root.get("delFlag"), Constant.DEL_NO));
                // 只查询审核通过，状态为3
                predicates.add(criteriaBuilder.equal(root.get("status"), Constant.SP_YES));
                return criteriaBuilder.and(predicates.toArray(new javax.persistence.criteria.Predicate[predicates.size()]));

            }
        };
        return woodStructureRepository.count(specification);
    }

    @Override
    public double area(AnalysisQueryVo analysisQueryVo) {
        Specification<FwWoodStructureEntity> specification = new Specification<FwWoodStructureEntity>() {
            @Override
            public javax.persistence.criteria.Predicate toPredicate(Root<FwWoodStructureEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<javax.persistence.criteria.Predicate> predicates = new ArrayList<>();
                if (analysisQueryVo != null) {
                    // 省
                    String belongtoProvince = analysisQueryVo.getBelongtoProvince();
                    if (!StringUtils.isEmpty(belongtoProvince)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoProvince"), belongtoProvince));
                    }
                    // 市
                    String belongtoCity = analysisQueryVo.getBelongtoCity();
                    if (!StringUtils.isEmpty(belongtoCity)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoCity"), belongtoCity));
                    }
                    // 区
                    String belongtoArea = analysisQueryVo.getBelongtoArea();
                    if (!StringUtils.isEmpty(belongtoArea)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoArea"), belongtoArea));
                    }
                    //建筑年代
                    String buildingAge = analysisQueryVo.getBuildingAge();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(buildingAge)) {
                        predicates.add(criteriaBuilder.equal(root.get("buildingAge"), buildingAge));
                    }
                    //任务名称
                    String taskName = analysisQueryVo.getTaskName();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(taskName)) {
                        String[] strArray = taskName.split(",");
                        List<String> list = Arrays.asList(strArray);
                        if (list != null && list.size() > 0){
                            predicates.add(root.get("taskName").in(list));
                        }
                    }
                    /*//抗震设防烈度
                    String nowFortificationIntensity = analysisQueryVo.getNowFortificationIntensity();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(nowFortificationIntensity)) {
                        predicates.add(criteriaBuilder.equal(root.get("fortifyStandard"), nowFortificationIntensity));
                    }*/
                    // 穿斗方式(横向穿斗贯穿整榀构架,无穿斗)
                    String cdType = analysisQueryVo.getCdType();
                    if (!StringUtils.isEmpty(cdType)) {
                        predicates.add(criteriaBuilder.equal(root.get("cdType"), cdType));
                    }
                    // 木柱梢径(大于150mm,小于等于150mm)
                    String mzsj = analysisQueryVo.getMzsj();
                    if (!StringUtils.isEmpty(mzsj)) {
                        predicates.add(criteriaBuilder.equal(root.get("mzsj"), mzsj));
                    }
                    // 围护墙体类型（土墙,砖墙,木板墙）
                    String wallType = analysisQueryVo.getWallType();
                    if (!StringUtils.isEmpty(wallType)) {
                        predicates.add(criteriaBuilder.equal(root.get("wallType"), wallType));
                    }
                    // 山尖墙体类型(土墙,砖墙,木板墙)
                    String sjqtType = analysisQueryVo.getSjqtType();
                    if (!StringUtils.isEmpty(sjqtType)) {
                        predicates.add(criteriaBuilder.equal(root.get("sjqtType"), sjqtType));
                    }
                    // 墙体厚度（按照≤120mm，120-240mm，240-360mm，≥360mm统计占比）
                    String wallThick = analysisQueryVo.getWallThick();
                    if (!StringUtils.isEmpty(wallThick)) {
                        if (Constant.LESS_120.equals(wallThick)) {
                            predicates.add(criteriaBuilder.le(root.get("wallThick"), 120));
                        }
                        if (Constant.BETWEEN_120_240.equals(wallThick)) {
                            predicates.add(criteriaBuilder.between(root.get("wallThick"), 120, 240));
                        }
                        if (Constant.BETWEEN_240_360.equals(wallThick)) {
                            predicates.add(criteriaBuilder.between(root.get("wallThick"), 240, 360));
                        }
                        if (Constant.MORE_360.equals(wallThick)) {
                            predicates.add(criteriaBuilder.ge(root.get("wallThick"), 360));
                        }
                    }
                    // 墙体圈梁（有圈梁,无圈梁）
                    String wallRingBeam = analysisQueryVo.getWallRingBeam();
                    if (!StringUtils.isEmpty(wallRingBeam)) {
                        predicates.add(criteriaBuilder.equal(root.get("wallRingBeam"), wallRingBeam));
                    }
                }
                // 有效标识，即为有效的
                predicates.add(criteriaBuilder.equal(root.get("delFlag"), Constant.DEL_NO));
                // 只查询审核通过，状态为3
                predicates.add(criteriaBuilder.equal(root.get("status"), Constant.SP_YES));
                return criteriaBuilder.and(predicates.toArray(new javax.persistence.criteria.Predicate[predicates.size()]));

            }
        };
        List<FwWoodStructureEntity> woodStructureEntityList = woodStructureRepository.findAll(specification);
        double count = 0.00;
        for (FwWoodStructureEntity woodStructureEntity : woodStructureEntityList) {
            double buildingAreaCount = 0.00;
            // 建筑面积
            if (!PlatformObjectUtils.isEmpty(woodStructureEntity.getBuildingArea())) {
                buildingAreaCount = woodStructureEntity.getBuildingArea().doubleValue();
                if (!PlatformObjectUtils.isEmpty(woodStructureEntity.getFloorNum())) {
                    buildingAreaCount = woodStructureEntity.getBuildingArea().doubleValue() *
                            woodStructureEntity.getFloorNum().intValue();
                }
            }
            count += buildingAreaCount;
        }
        Double.parseDouble(String.format("%.3f",count));
        return  Double.parseDouble(String.format("%.3f",count));
    }

    @Override
    public int areaCount(AnalysisQueryVo analysisQueryVo) {
        Specification<FwWoodStructureEntity> specification = new Specification<FwWoodStructureEntity>() {
            @Override
            public javax.persistence.criteria.Predicate toPredicate(Root<FwWoodStructureEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<javax.persistence.criteria.Predicate> predicates = new ArrayList<>();
                if (analysisQueryVo != null) {
                    // 省
                    String belongtoProvince = analysisQueryVo.getBelongtoProvince();
                    if (!StringUtils.isEmpty(belongtoProvince)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoProvince"), belongtoProvince));
                    }
                    // 市
                    String belongtoCity = analysisQueryVo.getBelongtoCity();
                    if (!StringUtils.isEmpty(belongtoCity)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoCity"), belongtoCity));
                    }
                    // 区
                    String belongtoArea = analysisQueryVo.getBelongtoArea();
                    if (!StringUtils.isEmpty(belongtoArea)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoArea"), belongtoArea));
                    }
                    // 穿斗方式(横向穿斗贯穿整榀构架,无穿斗)
                    String cdType = analysisQueryVo.getCdType();
                    if (!StringUtils.isEmpty(cdType)) {
                        predicates.add(criteriaBuilder.equal(root.get("cdType"), cdType));
                    }
                    // 木柱梢径(大于150mm,小于等于150mm)
                    String mzsj = analysisQueryVo.getMzsj();
                    if (!StringUtils.isEmpty(mzsj)) {
                        predicates.add(criteriaBuilder.equal(root.get("mzsj"), mzsj));
                    }
                    // 围护墙体类型（土墙,砖墙,木板墙）
                    String wallType = analysisQueryVo.getWallType();
                    if (!StringUtils.isEmpty(wallType)) {
                        predicates.add(criteriaBuilder.equal(root.get("wallType"), wallType));
                    }
                    // 山尖墙体类型(土墙,砖墙,木板墙)
                    String sjqtType = analysisQueryVo.getSjqtType();
                    if (!StringUtils.isEmpty(sjqtType)) {
                        predicates.add(criteriaBuilder.equal(root.get("sjqtType"), sjqtType));
                    }
                    // 墙体厚度（按照≤120mm，120-240mm，240-360mm，≥360mm统计占比）
                    String wallThick = analysisQueryVo.getWallThick();
                    if (!StringUtils.isEmpty(wallThick)) {
                        if (Constant.LESS_120.equals(wallThick)) {
                            predicates.add(criteriaBuilder.le(root.get("wallThick"), 120));
                        }
                        if (Constant.BETWEEN_120_240.equals(wallThick)) {
                            predicates.add(criteriaBuilder.between(root.get("wallThick"), 120, 240));
                        }
                        if (Constant.BETWEEN_240_360.equals(wallThick)) {
                            predicates.add(criteriaBuilder.between(root.get("wallThick"), 240, 360));
                        }
                        if (Constant.MORE_360.equals(wallThick)) {
                            predicates.add(criteriaBuilder.ge(root.get("wallThick"), 360));
                        }
                    }
                    // 墙体圈梁（有圈梁,无圈梁）
                    String wallRingBeam = analysisQueryVo.getWallRingBeam();
                    if (!StringUtils.isEmpty(wallRingBeam)) {
                        predicates.add(criteriaBuilder.equal(root.get("wallRingBeam"), wallRingBeam));
                    }
                }
                // 有效标识，即为有效的
                predicates.add(criteriaBuilder.equal(root.get("delFlag"), Constant.DEL_NO));
                // 只查询审核通过，状态为3
                predicates.add(criteriaBuilder.equal(root.get("status"), Constant.SP_YES));
                return criteriaBuilder.and(predicates.toArray(new javax.persistence.criteria.Predicate[predicates.size()]));
            }
        };
        List<FwWoodStructureEntity> woodStructureEntityList = woodStructureRepository.findAll(specification);
        int count = 0;
        for (FwWoodStructureEntity woodStructureEntity : woodStructureEntityList) {
            int buildingAreaCount = 0;
            // 建筑面积
            Double buildingArea = woodStructureEntity.getBuildingArea();
            if (buildingArea != null && !StringUtils.isEmpty(buildingArea.toString())) {
                buildingAreaCount = woodStructureEntity.getBuildingArea().intValue();
            }
            count += buildingAreaCount;
        }
        return count;
    }

    @Override
    public void export(List<String> idList, HttpServletResponse response) {
        List<FwWoodStructureEntity> list = woodStructureRepository.findInIdList(idList);
        // 深拷贝
        ArrayList<FwWoodStructureVo> vos = new ArrayList<>();
        for (FwWoodStructureEntity woodStructureEntity : list) {
            if(woodStructureEntity.getStatus().equals("1")){
                woodStructureEntity.setStatus("未审核");
            }else if(woodStructureEntity.getStatus().equals("2")){
                woodStructureEntity.setStatus("审核未通过");
            }else if(woodStructureEntity.getStatus().equals("3")){
                woodStructureEntity.setStatus("审核通过");
            }else if(woodStructureEntity.getStatus().equals("4")){
                woodStructureEntity.setStatus("省级退回");
            }else {
                woodStructureEntity.setStatus("中心退回");
            }
            String detailFile = woodStructureEntity.getDetailFile();
            StringBuilder file = new StringBuilder();
            if(org.apache.commons.lang3.StringUtils.isNotBlank(detailFile)){
                //获取数据真实的附件信息
                List<SysAttachmentEntity> byAttachIdsAndIsValid = sysAttachment.findByAttachIdsAndIsValid(Arrays.asList(detailFile.split(",")));
                if(PlatformObjectUtils.isNotEmpty(byAttachIdsAndIsValid)){
                    for (SysAttachmentEntity sysAttachmentEntity : byAttachIdsAndIsValid) {
                        String attachPath = sysAttachmentEntity.getAttachPath();
                        attachPath = attachPath.replace("/","");
                        file.append(attachPath).append(",");
                    }
                }
            }
            if(file.length()>0){
                String fileName = file.substring(0, file.length() - 1);
                woodStructureEntity.setDetailFile(fileName);
            }
            FwWoodStructureVo vo = new FwWoodStructureVo();
            BeanUtils.copyProperties(woodStructureEntity, vo);
            vos.add(vo);
        }
        // 导出
        EasyPoiExcelUtil.exportExcel(vos, "木结构信息统计", "木结构信息", FwWoodStructureVo.class, "木结构.xls", response);

    }

    /**
     * 批量存入库表并且返回错误数量
     *
     * @param taskName
     * @param taskId
     * @param list
     * @param message
     * @return
     */
    public int saveStructure(String taskName, String taskId, List<FwWoodStructureVo> list, StringBuilder message) {
        int count = 0;
        for (int i = 0; i < list.size(); i++) {
            FwWoodStructureEntity woodStructureEntity = new FwWoodStructureEntity();
            FwWoodStructureVo woodStructureVo = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(woodStructureVo, woodStructureEntity);
            String delflag="0";
            // 根据样本编号判断重复导入性
            FwWoodStructureEntity byWoodStructureNum = woodStructureRepository.findByWoodStructureNumAndDelFlag(woodStructureVo.getWoodStructureNum(),delflag);
            if (!StringUtils.isEmpty(byWoodStructureNum)) {
                message.append("样本编码" + woodStructureVo.getWoodStructureNum() + "已重复");
                ++count;
            } else {
                woodStructureEntity.setTaskId(taskId);
                woodStructureEntity.setTaskName(taskName);
                //导入数据后台生成编号
                String code = DivisionCache.structureCode();
                woodStructureEntity.setWoodStructureNum(code);
                save(woodStructureEntity);
            }
        }
        return count;
    }

    @Override
    public long buildingCount(AnalysisQueryVo analysisQueryVo) {
        Specification<FwStructureFormEntity> specification = new Specification<FwStructureFormEntity>() {
            @Override
            public javax.persistence.criteria.Predicate toPredicate(Root<FwStructureFormEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<javax.persistence.criteria.Predicate> predicates = new ArrayList<>();
                if (analysisQueryVo != null) {
                    // 省
                    String belongtoProvince = analysisQueryVo.getBelongtoProvince();
                    if (!StringUtils.isEmpty(belongtoProvince)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoProvince"), belongtoProvince));
                    }
                    // 市
                    String belongtoCity = analysisQueryVo.getBelongtoCity();
                    if (!StringUtils.isEmpty(belongtoCity)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoCity"), belongtoCity));
                    }
                    // 区
                    String belongtoArea = analysisQueryVo.getBelongtoArea();
                    if (!StringUtils.isEmpty(belongtoArea)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoArea"), belongtoArea));
                    }
                    //建筑年代
                    String buildingAge = analysisQueryVo.getBuildingAge();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(buildingAge)) {
                        predicates.add(criteriaBuilder.equal(root.get("buildingAge"), buildingAge));
                    }
                    //任务名称
                    String taskName = analysisQueryVo.getTaskName();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(taskName)) {
                        String[] strArray = taskName.split(",");
                        List<String> list = Arrays.asList(strArray);
                        if (list != null && list.size() > 0){
                            predicates.add(root.get("taskName").in(list));
                        }
                    }
                    // 审批类型
                    String status = analysisQueryVo.getStatus();
                    if (!StringUtils.isEmpty(status)) {
                        if ("审核通过".equals(status)) {
                            // 若为审核通过，查询status状态为3
                            predicates.add(criteriaBuilder.equal(root.get("status"), Constant.SP_YES));
                        } else if ("审核不通过".equals(status)) {
                            // 若为审核不通过，查询status状态为2
                            predicates.add(criteriaBuilder.equal(root.get("status"), Constant.SP_NOT));
                        } else {
                            //若为审核不通过，查询status状态为2
                            predicates.add(criteriaBuilder.equal(root.get("status"), Constant.DAI_SP));
                        }
                    }else {
                        //默认查询非未提交的
                        //predicates.add(criteriaBuilder.in(root.get("status"), (Constant.DAI_SP,Constant.DAI_SP));
                        CriteriaBuilder.In<Object> in = criteriaBuilder.in(root.get("status"));
                        in.value(Constant.DAI_SP);
                        in.value(Constant.SP_NOT);
                        in.value(Constant.SP_YES);
                        predicates.add(in);
                    }
                }
                // 有效标识，即为有效的
                predicates.add(criteriaBuilder.equal(root.get("delFlag"), Constant.DEL_NO));
                // 只查询审核通过，状态为3
                //predicates.add(criteriaBuilder.equal(root.get("status"), Constant.SP_YES));
                predicates.add(criteriaBuilder.equal(root.get("structureType"), Constant.WOOD_STRUCTURE));
                return criteriaBuilder.and(predicates.toArray(new javax.persistence.criteria.Predicate[predicates.size()]));

            }
        };
        return fwStructureFormRepository.count(specification);
    }

    @Override
    public double woodAreaCount(AnalysisQueryVo analysisQueryVo) {
        Specification<FwWoodStructureEntity> specification = new Specification<FwWoodStructureEntity>() {
            @Override
            public javax.persistence.criteria.Predicate toPredicate(Root<FwWoodStructureEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<javax.persistence.criteria.Predicate> predicates = new ArrayList<>();
                if (analysisQueryVo != null) {
                    // 省
                    String belongtoProvince = analysisQueryVo.getBelongtoProvince();
                    if (!StringUtils.isEmpty(belongtoProvince)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoProvince"), belongtoProvince));
                    }
                    // 市
                    String belongtoCity = analysisQueryVo.getBelongtoCity();
                    if (!StringUtils.isEmpty(belongtoCity)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoCity"), belongtoCity));
                    }
                    // 区
                    String belongtoArea = analysisQueryVo.getBelongtoArea();
                    if (!StringUtils.isEmpty(belongtoArea)) {
                        predicates.add(criteriaBuilder.equal(root.get("belongtoArea"), belongtoArea));
                    }
                    //建筑年代
                    String buildingAge = analysisQueryVo.getBuildingAge();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(buildingAge)) {
                        predicates.add(criteriaBuilder.equal(root.get("buildingAge"), buildingAge));
                    }
                    //任务名称
                    String taskName = analysisQueryVo.getTaskName();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(taskName)) {
                        predicates.add(criteriaBuilder.equal(root.get("taskName"), taskName));
                    }
                   /* //抗震设防烈度
                    String nowFortificationIntensity = analysisQueryVo.getNowFortificationIntensity();
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(nowFortificationIntensity)) {
                        predicates.add(criteriaBuilder.equal(root.get("fortifyStandard"), nowFortificationIntensity));
                    }*/
                    // 审批类型
                    String status = analysisQueryVo.getStatus();
                    if (!StringUtils.isEmpty(status)) {
                        if ("审核通过".equals(status)) {
                            // 若为审核通过，查询status状态为3
                            predicates.add(criteriaBuilder.equal(root.get("status"), Constant.SP_YES));
                        } else if ("审核不通过".equals(status)) {
                            // 若为审核不通过，查询status状态为2
                            predicates.add(criteriaBuilder.equal(root.get("status"), Constant.SP_NOT));
                        } else {
                            //若为审核不通过，查询status状态为2
                            predicates.add(criteriaBuilder.equal(root.get("status"), Constant.DAI_SP));
                        }
                    }else {
                        //默认查询非未提交的
                        //predicates.add(criteriaBuilder.in(root.get("status"), (Constant.DAI_SP,Constant.DAI_SP));
                        CriteriaBuilder.In<Object> in = criteriaBuilder.in(root.get("status"));
                        in.value(Constant.DAI_SP);
                        in.value(Constant.SP_NOT);
                        in.value(Constant.SP_YES);
                        predicates.add(in);
                    }
                }
                // 有效标识，即为有效的
                predicates.add(criteriaBuilder.equal(root.get("delFlag"), Constant.DEL_NO));
                // 只查询审核通过，状态为3
                //predicates.add(criteriaBuilder.equal(root.get("status"), Constant.SP_YES));
                return criteriaBuilder.and(predicates.toArray(new javax.persistence.criteria.Predicate[predicates.size()]));
            }
        };
        List<FwWoodStructureEntity> woodStructureEntityList = woodStructureRepository.findAll(specification);
        int count = 0;
        for (FwWoodStructureEntity woodStructureEntity : woodStructureEntityList) {
            int buildingAreaCount = 0;
            // 建筑面积
            Double buildingArea = woodStructureEntity.getBuildingArea();
            if (buildingArea != null && !StringUtils.isEmpty(buildingArea.toString())) {
                buildingAreaCount = woodStructureEntity.getBuildingArea().intValue();
            }
            count += buildingAreaCount;
        }
        return count;
    }
}
